<?php

namespace app\api\controller;

use app\admin\model\Article as ArticleModel;
use app\admin\model\UserArticleSupport;
use app\common\controller\Frontend;
use think\db\exception\DbException;

class Article extends Frontend
{
    protected $noNeedLogin = ['question'];

    protected $noNeedPermission = [];

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * @param ArticleModel $article
     * @param UserArticleSupport $userArticleSupport
     * @throws DbException
     */
    public function question(ArticleModel $article, UserArticleSupport $userArticleSupport)
    {
        $limit = $this->request->get('limit');
        $uid = $this->auth->getUserId();
        $cateId = get_sys_config('question_cate_id');
        $cateId = $cateId ?? 0;
        $list = $article
            ->where([
                'switch'  => 1,
                'cate_id' => $cateId,
            ])
            ->order('weight desc, id desc')
            ->hidden(array_merge(['cate_id'], $this->hidden))
            ->paginate($limit)
            ->each(function ($item) use ($uid, $userArticleSupport) {
                // 判断对用户是否有帮助
                $support = $userArticleSupport->where(['article_id' => $item['id'], 'user_id' => $uid])->value('type');
                $item['support'] = $support ?? 2;
                return $item;
            });
        $this->success('', $list);
    }
}